package com.leyou.item.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.pojo.Brand;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author wht
 */
@Service
public class BrandService {

    @Autowired
    private BrandMapper brandMapper;

    public PageResult<Brand> queryBrandByPage(Integer page, Integer rows, String sortBy, Boolean desc, String key) {

        //开启分页
        PageHelper.startPage(page, rows);

        Example example = new Example(Brand.class);

        Example.Criteria criteria = example.createCriteria();

        //拼接动态sql
        if (StringUtils.isNotBlank(key)) {
            criteria.andEqualTo("letter", key);
        }

        //判断是否有排序条件
        if (StringUtils.isNotBlank(sortBy)) {
            example.setOrderByClause(sortBy + (desc ? " DESC" : " ASC"));
            //相当于写好了order by 只需要加入排序字段以及排序方式　例如:order by id desc
//            String orderByClause = sortBy + (desc ? "DESC" : "ASC");
//            example.setOrderByClause(orderByClause);
        }

        Page<Brand> pageInfo = (Page<Brand>) this.brandMapper.selectByExample(example);

        return new PageResult<>(pageInfo.getTotal(), pageInfo);
    }

    @Transactional
    public void saveBrand(Brand brand, List<Long> cids) {
        //保存后主键回显
        this.brandMapper.insertSelective(brand);

        //循环保存分类和品牌的关系
        cids.forEach(cid -> this.brandMapper.insertCategoryBrand(cid, brand.getId()));
    }
}
